from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, desc
from datetime import datetime, timedelta
from typing import List, Optional
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import auth
import database
import schemas
from routers.auth import get_db, get_current_admin_user
import math

router = APIRouter()

@router.get("/users", response_model=List[schemas.UserResponse])
async def get_all_users(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=1000, description="返回的记录数"),
    search: Optional[str] = Query(None, description="搜索用户名、邮箱或医院"),
    admin_user: database.User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """获取所有用户列表（仅管理员）"""
    query = db.query(database.User)
    
    if search:
        search_pattern = f"%{search}%"
        query = query.filter(
            or_(
                database.User.username.like(search_pattern),
                database.User.email.like(search_pattern),
                database.User.hospital.like(search_pattern)
            )
        )
    
    users = query.offset(skip).limit(limit).all()
    return users

@router.get("/users/{user_id}", response_model=schemas.UserResponse)
async def get_user_by_id(
    user_id: int,
    admin_user: database.User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """获取指定用户信息（仅管理员）"""
    user = db.query(database.User).filter(database.User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    return user

@router.patch("/users/{user_id}/role")
async def update_user_role(
    user_id: int,
    role: schemas.UserRole,
    admin_user: database.User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """更新用户角色（仅管理员）"""
    user = db.query(database.User).filter(database.User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 防止管理员修改自己的角色
    if user.id == admin_user.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="无法修改自己的角色"
        )
    
    user.role = role
    user.updated_at = datetime.utcnow()
    db.commit()
    db.refresh(user)
    
    return {"message": f"用户 {user.username} 的角色已更新为 {role}"}

@router.patch("/users/{user_id}/status")
async def update_user_status(
    user_id: int,
    is_active: bool,
    admin_user: database.User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """更新用户状态（启用/禁用）（仅管理员）"""
    user = db.query(database.User).filter(database.User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 防止管理员禁用自己
    if user.id == admin_user.id and not is_active:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="无法禁用自己的账户"
        )
    
    user.is_active = is_active
    user.updated_at = datetime.utcnow()
    db.commit()
    db.refresh(user)
    
    status_text = "启用" if is_active else "禁用"
    return {"message": f"用户 {user.username} 已{status_text}"}

@router.get("/login-records", response_model=schemas.PaginatedResponse)
async def get_login_records(
    user_id: Optional[int] = Query(None, description="用户ID"),
    username: Optional[str] = Query(None, description="用户名"),
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    status: Optional[str] = Query(None, description="登录状态"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页记录数"),
    admin_user: database.User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """获取登录记录（仅管理员）"""
    query = db.query(database.LoginRecord, database.User.username).join(
        database.User, database.LoginRecord.user_id == database.User.id, isouter=True
    )
    
    # 应用过滤条件
    if user_id:
        query = query.filter(database.LoginRecord.user_id == user_id)
    
    if username:
        query = query.filter(database.User.username.like(f"%{username}%"))
    
    if start_date:
        query = query.filter(database.LoginRecord.login_time >= start_date)
    
    if end_date:
        query = query.filter(database.LoginRecord.login_time <= end_date)
    
    if status:
        query = query.filter(database.LoginRecord.status == status)
    
    # 获取总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * page_size
    records_with_username = query.order_by(desc(database.LoginRecord.login_time)).offset(offset).limit(page_size).all()
    
    # 格式化响应
    items = []
    for record, username in records_with_username:
        record_dict = {
            "id": record.id,
            "user_id": record.user_id,
            "username": username or "未知用户",
            "login_time": record.login_time,
            "ip_address": record.ip_address,
            "user_agent": record.user_agent,
            "status": record.status
        }
        items.append(record_dict)
    
    total_pages = math.ceil(total / page_size)
    
    return {
        "total": total,
        "page": page,
        "page_size": page_size,
        "total_pages": total_pages,
        "items": items
    }

@router.get("/processing-records", response_model=schemas.PaginatedResponse)
async def get_processing_records(
    user_id: Optional[int] = Query(None, description="用户ID"),
    username: Optional[str] = Query(None, description="用户名"),
    operation_type: Optional[str] = Query(None, description="操作类型"),
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    status: Optional[str] = Query(None, description="处理状态"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页记录数"),
    admin_user: database.User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """获取数据处理记录（仅管理员）"""
    query = db.query(database.DataProcessingRecord, database.User.username).join(
        database.User, database.DataProcessingRecord.user_id == database.User.id, isouter=True
    )
    
    # 应用过滤条件
    if user_id:
        query = query.filter(database.DataProcessingRecord.user_id == user_id)
    
    if username:
        query = query.filter(database.User.username.like(f"%{username}%"))
    
    if operation_type:
        query = query.filter(database.DataProcessingRecord.operation_type.like(f"%{operation_type}%"))
    
    if start_date:
        query = query.filter(database.DataProcessingRecord.processing_time >= start_date)
    
    if end_date:
        query = query.filter(database.DataProcessingRecord.processing_time <= end_date)
    
    if status:
        query = query.filter(database.DataProcessingRecord.status == status)
    
    # 获取总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * page_size
    records_with_username = query.order_by(desc(database.DataProcessingRecord.processing_time)).offset(offset).limit(page_size).all()
    
    # 格式化响应
    items = []
    for record, username in records_with_username:
        record_dict = {
            "id": record.id,
            "user_id": record.user_id,
            "username": username or "未知用户",
            "operation_type": record.operation_type,
            "operation_details": record.operation_details,
            "file_name": record.file_name,
            "processing_time": record.processing_time,
            "duration_ms": record.duration_ms,
            "status": record.status,
            "error_message": record.error_message
        }
        items.append(record_dict)
    
    total_pages = math.ceil(total / page_size)
    
    return {
        "total": total,
        "page": page,
        "page_size": page_size,
        "total_pages": total_pages,
        "items": items
    }

@router.get("/statistics")
async def get_statistics(
    admin_user: database.User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """获取系统统计信息（仅管理员）"""
    # 用户统计
    total_users = db.query(database.User).count()
    active_users = db.query(database.User).filter(database.User.is_active == True).count()
    admin_users = db.query(database.User).filter(database.User.role == "admin").count()
    
    # 最近7天登录统计
    seven_days_ago = datetime.utcnow() - timedelta(days=7)
    recent_logins = db.query(database.LoginRecord).filter(
        database.LoginRecord.login_time >= seven_days_ago,
        database.LoginRecord.status == "success"
    ).count()
    
    # 最近24小时处理记录统计
    twenty_four_hours_ago = datetime.utcnow() - timedelta(hours=24)
    recent_processing = db.query(database.DataProcessingRecord).filter(
        database.DataProcessingRecord.processing_time >= twenty_four_hours_ago
    ).count()
    
    # 失败登录统计
    failed_logins_today = db.query(database.LoginRecord).filter(
        database.LoginRecord.login_time >= datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0),
        database.LoginRecord.status == "failed"
    ).count()
    
    return {
        "users": {
            "total": total_users,
            "active": active_users,
            "admin": admin_users
        },
        "activity": {
            "recent_logins_7d": recent_logins,
            "recent_processing_24h": recent_processing,
            "failed_logins_today": failed_logins_today
        }
    } 